from fastapi import APIRouter
import json
from pathlib import Path
from datetime import datetime
import pandas as pd
import os
import sys
print_app = APIRouter()

LAST_ID = ""

# 获取当前脚本的绝对路径
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
@print_app.get("/get_txt")
async def get_txt(print_count: int):
    global LAST_ID
    input_str = ""
    exe_dir_path = os.path.join(base_path, "config.txt")
    # exe_dir_path = r"D:\rust\vue-plugin-hiprint-start\src-tauri\config.txt"
    # 获取本地时区的当前日期和时间
    today = datetime.now()
    # 格式化日期为 "yyyyMMdd"
    formatted_date = today.strftime("%Y%m%d")

    try:
        with open(exe_dir_path, 'r', encoding='utf-8') as file:
            input_str = file.read()

        arr = input_str.split(",")
        last_id = int(arr[3])  # 上次打印的最后序号
        d2 = int(arr[2])
        current_date=int(formatted_date)
        if current_date>d2: # 如果当前日期大于上次打印的日期, 则重置序号
            last_id=0
        num = print_count  # 要打印的数量
        print_data = []

        for _ in range(num):
            s1 = arr[1] + arr[2]  # 条形码前缀加上日期
            last_id += 1
            last_id_str = str(last_id)
            s1 += last_id_str.zfill(4)  # 补齐四位数

            print_data.append({
                "name": s1,
                "txt_value": arr[0],
            })

        json_str = json.dumps(print_data)
        new_str = f"{arr[0]},{arr[1]},{formatted_date},{last_id},{num},//标签名称-条码前缀-日期-最后序号-打印数量"
        LAST_ID = new_str
        return {
            "code": 200,
            "status": "ok",
            "message": "获取数据成功",
            "data": json_str
        }

    except Exception as e:
        return {
            "code": 500,
            "status": "error",
            "message": str(e),
            "data": None
        }


@print_app.post("/save_last_id")
async def save_last_id():
    global LAST_ID
    exe_dir_path = Path(os.path.join(base_path, "config.txt"))
    # exe_dir_path = Path(r"D:\rust\vue-plugin-hiprint-start\src-tauri\config.txt")

    try:
        # 'w'模式会覆盖原有文件内容
        with exe_dir_path.open('w', encoding='utf-8') as file:
            file.write(LAST_ID)
        return {
            "code": 200,
            "status": "ok",
            "message": "保存成功",
            "data": None
        }
    except Exception as e:
        return {
            "code": 500,
            "status": "error",
            "message": str(e),
            "data": None
        }


@print_app.get("/hw_print")
async def hw_print():
    try:
        excel_path = os.path.join(base_path, "货位标签模板.xlsx")
        df = pd.read_excel(excel_path, sheet_name="Sheet1", usecols=["货位"], engine="calamine")
        if df.empty:
            return {
                "code": 500,
                "status": "error",
                "message": "没有数据",
                "data": None
            }

        print_data = []
        for index, row in df.iterrows():
            print_data.append({
                "name": row["货位"],
                "txt_value": '',
            })
        json_str = json.dumps(print_data)
        return {
            "code": 200,
            "status": "ok",
            "message": "获取数据成功",
            "data": json_str
        }
    except Exception as e:
        return {
            "code": 500,
            "status": "error",
            "message": str(e),
            "data": None
        }